package ift605.EquationWithTrainingAgents.agent;

import java.io.IOException;
import java.util.Random;

import ift605.EquationWithTrainingAgents.struct.LearningMessage;
import udes.ds.agent.AbstractEquation;
import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;

public class Papa extends Agent{
	private static final long serialVersionUID = 1L;
	
	private static final double EPSILON = 0.00000001d;
	private static final double THRESHOLD_OF_ACCEPTANCE = 0.1d; //Do something intelligent here
	private double[] random = new double[]
			{
				.10d,
				.15d,
				.35d,
				.43d,
				.78d,
				.89d,
				.65d,
				.32d,
				.905d,
				.1187d,
				.15d,
			};
	
	@Override
	public void setup() {
		//Behavior taking request from "learning pool" and evaluate eq
		addBehaviour(new VerifiyAnswerBehavior());
	}
	
	private class VerifiyAnswerBehavior extends CyclicBehaviour{
		private static final long serialVersionUID = 1L;

		@Override
		public void action() {
			try
			{
				ACLMessage request = null;
				MessageTemplate mt = MessageTemplate.MatchConversationId(LearningMessage.VERIFY);
				request = receive(mt);
				
				if(request != null)
				{
					LearningMessage requestMess = null;
					requestMess = (LearningMessage)request.getContentObject();
					
					AbstractEquation based = requestMess.base;
					AbstractEquation derived = requestMess.derived;					
					
					boolean isValid = true;
					for(int i = 0; i < random.length && isValid; i++)
					{
						double testingValue = random[i];
						double valueOfBase = (based.getFunctionValue(testingValue + EPSILON) - based.getFunctionValue(testingValue - EPSILON))/(2.d*EPSILON);
						double valueOfDerive = derived.getFunctionValue(testingValue);
						isValid = THRESHOLD_OF_ACCEPTANCE > Math.abs(valueOfBase - valueOfDerive);
						
/*
						System.out.println("Checking :: {" + Math.abs(valueOfBase - valueOfDerive));
						based.printUserReadable();
						derived.printUserReadable();*/
						
					}
					
					
					requestMess.isResolved = isValid;
					
					ACLMessage response = new ACLMessage(requestMess.requestID);
					response.addReceiver(request.getSender());
					response.setConversationId(LearningMessage.VERIFY_ANSWER);
					response.setContentObject(requestMess);
					send(response);
					
					if(requestMess.isResolved)
					{
						//System.out.println("Papa a tjs raison");
					}
				}
				else
				{
					block();
				}
			}
			catch (UnreadableException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}	
		}
	}
}
